package com.lg.system.main.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.pool.DruidDataSource;
import com.lg.common.annotation.Logs;
import com.lg.common.base.BaseController;
import com.lg.system.main.service.LoginService;
import com.lg.system.user.entity.UserEntity;
import com.lg.system.user.service.UserService;
import com.lg.utils.MD5Utils;
import com.lg.utils.R;
@RestController
public class LoginController extends BaseController<UserEntity, UserService> {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	LoginService loginService;
	
	 @Autowired
	 DruidDataSource druidDataSource;

	
	@GetMapping({ "/" })
	ModelAndView welcome() {
		ModelAndView mv= new ModelAndView("login");
		if(getSubjct().isAuthenticated()){
			mv.addObject("menus", loginService.menus(getUserId()));
			mv.setViewName("index");
		}
		return mv;
	}
	
	@GetMapping("/login")
	ModelAndView login() {
		return new ModelAndView("login");
	}
	
	@PostMapping("/login")
	R ajaxLogin(String uname, String upass) {
		upass = MD5Utils.encrypt(uname, upass);
		UsernamePasswordToken token = new UsernamePasswordToken(uname, upass);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			return R.ok("登录成功");
		} catch (AuthenticationException e) {
			logger.info("登录异常");
			return R.error(e.getMessage());
		}
	}
	
	@GetMapping({ "/index" })
	ModelAndView index() {
		ModelAndView mv= new ModelAndView("index");
		mv.addObject("menus", loginService.menus(getUserId()));
		return mv;
	}
	
	@RequestMapping("/main")
	public ModelAndView main(){
		ModelAndView mView=new ModelAndView("main");
		return mView;
	}

}
